package org.carry.god.module.system.controller.auth;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.carry.god.framework.common.exception.utils.ServiceExceptionUtil;
import org.carry.god.framework.common.pojo.CommonResult;
import org.carry.god.module.system.api.user.UserRespDTO;
import org.carry.god.module.system.controller.auth.vo.AuthLoginReqVO;
import org.carry.god.module.system.controller.auth.vo.AuthLoginRespVO;
import org.carry.god.module.system.service.UserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.carry.god.module.system.enums.ErrorCodeConstants.USER_NAME_NOT_EXISTS;
import static org.carry.god.module.system.enums.ErrorCodeConstants.USER_PASSWORD_ERROR;

/**
 * @author wanglei
 */
@Tag(name = "认证管理")
@RestController
@RequestMapping("/system/auth")
public class AuthController {
    @Resource
    private UserService userService;
    @PostMapping("/login")
    @Operation(summary = "登录认证")
    public CommonResult<AuthLoginRespVO> login(@Valid @RequestBody AuthLoginReqVO loginReqVO) {
        UserRespDTO user = userService.getUserByUsername(loginReqVO.getUsername());
        if (user == null) {
            throw ServiceExceptionUtil.exception(USER_NAME_NOT_EXISTS);
        }
        if (loginReqVO.getPassword().equals(user.getPassword())) {
            StpUtil.login(user.getId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            AuthLoginRespVO loginRespVO = new AuthLoginRespVO();
            loginRespVO.setAccessToken(tokenInfo.getTokenValue());
            return CommonResult.success(loginRespVO);
        } else {
            throw ServiceExceptionUtil.exception(USER_PASSWORD_ERROR);
        }
    }
}
